package cn.net.yato.picture.config.shiro;

import cn.net.yato.picture.biz.SysBiz;
import cn.net.yato.picture.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author yato
 */
public class PhoneAndVerificationCodeShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysBiz sysBiz;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new UserNamePasswordRealm().getAuthorizationInfo(principals);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        PhoneAndVerificationCodeToken phoneAndVerificationCodeToken=(PhoneAndVerificationCodeToken) token;
        String phone = (String) phoneAndVerificationCodeToken.getPrincipal();
        User user = sysBiz.loginByPhoneBiz(phone);
        if (user==null){
            throw new UnknownAccountException("手机号码暂未绑定呢!");
        }
        return new SimpleAuthenticationInfo(user,phone,getName());
    }
 
    /**
     * 用来判断是否使用当前的 realm
     * @param authenticationToken 传入的token
     * @return true就使用，false就不使用
     */
    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof PhoneAndVerificationCodeToken;
    }
}
